import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore(
  'useUserStore',
  () => {
    // 用户信息
    const user = ref({
      user_id: ''
    })

    // 设置用户信息
    const setUser = (u) => {
      console.log('设置用户', u)
      user.value = u
    }

    // 用户token
    const token = ref('')
    // 存储token
    const setToken = (t) => {
      console.log('设置token', t)
      token.value = t
    }
    // 移除token
    const removeToken = () => {
      token.value = ''
    }

    // 用户搜索记录
    const historyList = ref([])

    // 增加搜索记录
    const addHistory = (history) => {
      // 数据去重
      const goods = historyList.value.find(
        (item) => item.goodsName === history.goodsName.value
      )

      if (goods) return
      historyList.value.unshift(history)
    }

    // 清空搜索记录
    const clearHistory = () => {
      historyList.value = []
    }

    return {
      token,
      setToken,
      removeToken,
      user,
      setUser,
      historyList,
      addHistory,
      clearHistory
    }
  },
  {
    persist: true // 持久化
  }
)
